import numpy as np
import cv2

def get_blur_mask(all_events_img, ksize=3, thresh=1):
    """
    生成更模糊、更连续的模糊掩码(blur mask)
    :param all_events_img: 包含所有事件的图像(uint8或int32)
    :param ksize: 中值滤波核大小
    :param thresh_method: 'otsu' 或 'fixed'
    :param fixed_thresh: 固定阈值(仅在thresh_method='fixed'时有效)
    :param dilate_kernel: 膨胀核大小
    :return: blur_mask(二值图像)
    """
    blurred = cv2.medianBlur(all_events_img.astype(np.uint8), ksize)
    return blurred < thresh

def get_morph_mask(all_events_img, rect_w=15, rect_h=5, ksize1=7, ksize2=7):
    """
    生成形态掩码(morph mask)
    :param all_events_img: 包含所有事件的图像(uint8或int32)
    :return: morph_mask(二值图像)
    """
    img = all_events_img.astype(np.uint8)
    # 第一次闭运算：水平矩形核
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (rect_w, rect_h))
    temp = cv2.morphologyEx(img, cv2.MORPH_CLOSE, horizontal_kernel)
    # 一次闭运算：圆盘核
    disk_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ksize1, ksize1))
    temp = cv2.morphologyEx(temp, cv2.MORPH_CLOSE, disk_kernel)
    # 一次开运算：小圆盘核
    small_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ksize2, ksize2))
    morph_mask = cv2.morphologyEx(temp, cv2.MORPH_OPEN, small_kernel)
    # 二值化
    morph_mask = (morph_mask > 0).astype(np.uint8)
    return morph_mask

def get_largest_blob(mask):
    """
    只保留最大连通区域
    :param mask: 二值图像
    :return: 仅含最大连通区域的掩码
    """
    num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
    if num_labels <= 1:
        return mask
    largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
    largest_blob = (labels == largest_label).astype(np.uint8)
    return largest_blob

def create_eyelash_mask(all_events_img, eyelid_glint_mask, blur_ksize=3, blur_thresh=1, morph_rect_w=15, morph_rect_h=5, morph_ksize1=7, morph_ksize2=7):
    """
    生成睫毛掩码
    :param all_events_img: 包含所有事件的图像
    :param eyelid_glint_mask: 眼睑和光斑掩码
    :param blur_thresh_method: 'otsu' 或 'fixed'
    :param morph_horizontal: 水平核宽度
    :return: eyelash_mask
    """
    # 1. 生成模糊掩码
    blur_mask = get_blur_mask(all_events_img, ksize=blur_ksize, thresh=blur_thresh)
    # 2. 生成形态掩码
    morph_mask = get_morph_mask(all_events_img, rect_w=morph_rect_w, rect_h=morph_rect_h, ksize1=morph_ksize1, ksize2=morph_ksize2)
    # 3. 掩码并集与模糊掩码交集
    eyelash_mask = (eyelid_glint_mask | morph_mask) & blur_mask
    return get_largest_blob(eyelash_mask)
